package com.luboyan.CBillbill.service.user.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.luboyan.CBillbill.mapper.user.UserMomentsMapper;
import com.luboyan.CBillbill.dao.user.UserMoments;
import com.luboyan.CBillbill.service.user.UserMomentsService;
import com.luboyan.CBillbill.util.RocketMQUtil;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

import static com.luboyan.CBillbill.util.enums.UserInfoEnum.TOPIC_MOMENTS;

/**
 * 用户动态管理
 */
@Service
public class UserMomentsServiceImpl implements UserMomentsService {

    @Autowired
    private UserMomentsMapper userMomentsMapper;

    @Autowired
    private ApplicationContext applicationContext; //需要拿到rocketmqConfig中注册好的生产者和消费者的bean

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 新增用户动态
     */
    @Override
    public void addUserMoments(UserMoments userMoments) throws Exception {
        userMoments.setCreateTime(new Date());
        userMomentsMapper.insert(userMoments);

        //推送消息
        DefaultMQProducer producer = (DefaultMQProducer) applicationContext.getBean("momentsProducer");
        Message message = new Message(TOPIC_MOMENTS.getParameter(), //消息主题,注意是消费者订阅的主题
                JSONObject.toJSONString(userMoments).getBytes(StandardCharsets.UTF_8));
        //调用工具类中的发送消息方法，注意是异步
        RocketMQUtil.asyncSendMsg(producer, message);
    }

    /**
     * 获取当前用户的订阅用户的动态
     */
    @Override
    public List<UserMoments> getUserSubscribedMoments(Long userId) {
        //从redis中获取，key对应配置类中写入redis的key
        String key = "subscribed-" + userId;
        String StrList = redisTemplate.opsForValue().get(key);
        return JSONArray.parseArray(StrList, UserMoments.class);
    }
}
